package com.sugon.modules.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.cait.service.ResCenterClient;
import com.cait.service.rescenter.ResultMessage;
import com.cait.service.rescenter.UserInfo;
import com.sugon.modules.sys.service.IResCenterAuthenticator;
import com.sugon.service.SysConfigService;
import com.sugon.utils.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.rmi.RemoteException;

/**
 * @author ： YuXD
 * @description： 长安统一资源认证器实现类
 * @date ： 2021-06-15 下午 3:56
 * @version: 1.0
 */
@Slf4j
@Service
public class ResCenterAuthenticatorImpl implements IResCenterAuthenticator {

    @Autowired
    private SysConfigService configService;

    @Override
    public ResultMessage doResCenterAuthenticate(String username, String password) {
        String host = testResCenterClientConnect();
        ResultMessage resultMessage = null;
        try {
            resultMessage = ResCenterClient.getResCenterApi().userLogin(username, password, host);
            log.info(JSON.toJSONString(resultMessage));
        } catch (RemoteException e) {
            log.error("执行统一认证登陆时发生异常", e);
        }
        return resultMessage;
    }


    @Override
    public UserInfo getUserByToken(String identityToken) {
        // 认证中心应用ID
        testResCenterClientConnect();
        try {
            // 执行认证
            return ResCenterClient.getResCenterApi().getUserByToken(identityToken);
        } catch (RemoteException e) {
            log.error("根据identityToken获取用户信息时发生异常", e);
        }
        return null;
    }


    /**
     * 测试连接认证资源中心是否成功
     * 并进行远程连接初始化操作
     *
     * @return
     */
    private String testResCenterClientConnect() {
        // 认证中心应用ID
        String appId = configService.getValue("APPID", "");
        // 认证资源中心服务接口地址  http://cmpuat.changan.com/rescenter/services/ResCenterApi2
        String rescenterServiceUrl = configService.getRemoteServiceHost() + "/rescenter/services/ResCenterApi2";
        log.info("连接认证资源中心，APPID：{}，认证地址：{}", appId, rescenterServiceUrl);
        // 获取本机域名
        String host = configService.getValue("HOST", "");
        if (StrUtil.isEmpty(appId) || StrUtil.isEmpty(rescenterServiceUrl) || StrUtil.isEmpty(host)) {
            throw new RRException("认证信息配置不全!");
        }
        // 测试是否通
        boolean connectResult = ResCenterClient.connect(appId, rescenterServiceUrl);
        if (!connectResult) {
            throw new RRException("认证中心通信失败,请稍后重试!");
        }
        return host;
    }

    @Override
    public boolean checkIdentityToken(String identityToken) {
        String host = testResCenterClientConnect();
        try {
            return ResCenterClient.getResCenterApi().checkIdentityToken(identityToken);
        } catch (RemoteException e) {
            log.error("检查令牌是否合法时发生异常", e);
        }
        return false;
    }

    @Override
    public boolean checkIdentityToken(HttpServletRequest request, HttpServletResponse response) {
        String host = testResCenterClientConnect();
        return ResCenterClient.getIsAuthenticated(request, response);
    }

    @Override
    public String getIdentityToken(HttpServletRequest request, HttpServletResponse response) {
        return ResCenterClient.getIdentityToken(request, response);
    }

    @Override
    public String getLoginAgentUrlByRedrect(String redirecturl) {
        String host = testResCenterClientConnect();
        // 认证中心应用ID
        String appId = configService.getValue("APPID", "");
        try {
            return ResCenterClient.getResCenterApi().getLoginAgentUrlByRedrect(appId, redirecturl);
        } catch (RemoteException e) {
            log.error("检查令牌是否合法时发生异常", e);
        }
        return "false";
    }
}
